﻿using Microsoft.CodeAnalysis.Scripting;
using OrBitDataModule.FileHelper;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OrBitDataModule.Common
{
    public static class FileUtils
    {
        /// <summary>
        /// 移动到备份目录,如果文件已存在，文件名加上时分秒
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="dstPath"></param>
        public static string MoveFile(string srcPath, string dstPath)
        {
            try
            {
                string subDir = DateTime.Now.ToString("yyyyMMdd");
                string path = Path.Combine(dstPath, subDir);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string dstFileName = Path.Combine(path, Path.GetFileName(srcPath));
                if (File.Exists(dstFileName))
                {
                    dstFileName = Path.Combine(path, Path.GetFileNameWithoutExtension(srcPath) + DateTime.Now.ToString("_HHmmss") + Path.GetExtension(srcPath));
                }
                File.Move(srcPath, dstFileName);
                return dstFileName;
            }
            catch (Exception ex)
            {
                throw new Exception($"源文件：{srcPath},转移至备份目录：{dstPath} 出现异常！信息：{ex.Message}");
            }
        }

        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsFileInUse(string filePath)
        {
            try
            {
                using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    fs.Close();
                }
                return false; // 文件没有被占用
            }
            catch (IOException)
            {
                return true; // 文件被占用
            }
        }

        /// <summary>
        /// 获取文件夹所有文件
        /// </summary>
        /// <param name="folderPath">遍历的文件夹</param>
        /// <param name="filePattern">通配符模式，*表示任意字符，例如*EF*.txt表示文件名中包含"EF"的.txt文件</param>
        /// <param name="includeSubdirectories">是否遍历子目录</param>
        /// <returns></returns>
        public static List<string> TraverseFolder(string folderPath, string filePattern, bool includeSubdirectories)
        {
            List<string> fileList = new List<string>();

            try
            {
                // 获取指定路径下的所有文件
                string[] files = Directory.GetFiles(folderPath, "*", includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                // 将符合通配符模式的文件添加到集合中
                foreach (string file in files)
                {
                    // 检查文件名是否匹配通配符模式
                    if (IsFileMatchPattern(file, filePattern))
                    {
                        fileList.Add(file);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            return fileList;
        }

        private static bool IsFileMatchPattern(string filePath, string filePattern)
        {
            string fileName = Path.GetFileName(filePath);

            // 将通配符模式转换为正则表达式
            string regexPattern = "^" + Regex.Escape(filePattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";

            // 使用正则表达式检查文件名是否匹配模式
            return Regex.IsMatch(fileName, regexPattern);
        }

        /// <summary>
        /// 验证输入的文件名后缀是否符合规则
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static bool IsValidFilterFormat(string filter)
        {
            string[] parts = filter.Split('|');
            return parts.All(IsValidFileExtension);
        }

        private static bool IsValidFileExtension(string extension)
        {
            string pattern = @"^.+\..+$";
            return System.Text.RegularExpressions.Regex.IsMatch(extension, pattern);
        }

        /// <summary>
        /// 异步读取文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task<string> ReadTextFileAsync(string fileName, Encoding encoding)
        {
            try
            {
                if (IsFileInUse(fileName))
                {
                    await Task.Delay(3000);
                }
                using (StreamReader reader = new StreamReader(fileName, encoding))
                {
                    return await reader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 读取Excel，获取XML字符串
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ReadExcelString(string fileName)
        {
            try
            {
               return ExcelUtils.GetDataSet(fileName).GetXml();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 读取Excel，获取XML字符串
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ReadCSVString(string fileName, Encoding encoding)
        {
            try
            {
                DataSet dataSet = new DataSet("DataSet");
                dataSet.Tables.Add(ExcelUtils.ReadCsv(fileName, true, encoding));
                return dataSet.GetXml();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
